<template>
    <div class="add-address-container">
        <nut-form>
            <nut-form-item label="姓名">
                <nut-input v-model="formData.linkman" :border="false" placeholder="请输入姓名" type="text" />
            </nut-form-item>
            <!-- <nut-divider :style="{ color: '#f7f8f9', borderColor: '#f7f8f9', padding: '0 16px' }"></nut-divider> -->
            <nut-form-item label="手机号">
                <nut-input v-model="formData.phone" :border="false" placeholder="请输入手机号" type="text" />
            </nut-form-item>

        </nut-form>

        <nut-cell title="选择省份" :desc="province" type="custom2" is-link @click="showAddress1"></nut-cell>

        <nut-popup v-model:visible="showPopup1" position="bottom">
            <nut-picker v-model="provinceId" :columns="address.province" title="请选择省份" @confirm="confirm1"
                @cancel="showPopup1 = false" />
        </nut-popup>

        <nut-cell title="选择市" :desc="city" type="custom2" is-link @click="showAddress2"></nut-cell>
        <nut-popup v-model:visible="showPopup2" position="bottom">
            <nut-picker v-model="cityId" :columns="address.city" title="请选择城市" @confirm="confirm2"
                @cancel="showPopup2 = false" />
        </nut-popup>

        <nut-cell title="选择区(县)" :desc="town" type="custom2" is-link @click="showAddress3"></nut-cell>
        <nut-popup v-model:visible="showPopup3" position="bottom">
            <nut-picker v-model="townId" :columns="address.town" title="请选择区(县)" @confirm="confirm3"
                @cancel="showPopup3 = false" />
        </nut-popup>

        <nut-textarea v-model.trim="formData.address" placeholder="请输入详细地址" :max-length="50" :rows="4" />

        <div class="default-box">
            <nut-cell>
                <nut-checkbox v-model="defaultState"> 设为默认收货地址
                </nut-checkbox>


            </nut-cell>
            <nut-cell>
                <nut-checkbox v-model="defaultRefundState"> 设为默认退货地址 </nut-checkbox>

            </nut-cell>
        </div>
        <div class="footer-btn">

            <nut-button size="normal" block color="linear-gradient(to right, #5232B7,#7237BC)" @click="saveAddress"
                type="primary">{{ addressId ? '修改地址' : '保存地址' }}</nut-button>
        </div>

    </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import * as addressApi from '../../api/address'
import pinyin from "pinyin";
import Taro from '@tarojs/taro';
const router = Taro.useRouter();



const showPopup1 = ref(false)
const showPopup2 = ref(false)
const showPopup3 = ref(false)
const addressId = ref("")
const address = reactive({
    province: [

    ],
    city: [

    ],
    town: []
})


onMounted(() => {
    addressId.value = router.params.id;
    if (addressId.value) {
        getAddressDetail()
    }

    getLevelArea(0, 0)
})
const province = ref('')
const city = ref('')
const town = ref('')

const provinceId = ref()
const cityId = ref()
const townId = ref()
const defaultState = ref(false)
const defaultRefundState = ref(false)
//编辑的时候获取详情
const getAddressDetail = async () => {
    try {
        const { data, state, message } = await addressApi.AddressDetail({ id: addressId.value })
        if (state == 200) {
            formData.value.linkman = data.linkman
            formData.value.phone = data.phone
            formData.value.address = data.address
            province.value = data.provinceName
            city.value = data.cityName
            town.value = data.areaName
            provinceId.value = [data.province]
            cityId.value = [data.city]
            townId.value = [data.areaCode]
            defaultState.value = data.defaultState == 1 ? true : false
            defaultRefundState.value = data.defaultRefundState == 1 ? true : false
            getLevelArea(1, provinceId.value)
            getLevelArea(2, cityId.value)


        } else {
            Taro.showToast({
                title: message,
                icon: 'none',
                duration: 2000
            })
        }
    } catch (error) {
        Taro.showToast({
            title: "获取地址详情失败~",
            icon: 'none',
            duration: 2000
        })

    }

}
//获取城市区域
const getLevelArea = async (level, parentId) => {

    try {
        const { data, state, message } = await addressApi.getArea({ parentId })
        if (state == 200) {
            if (level == 0) {
                console.log(data, "data");
                let arr = data.map(item => {
                    return {
                        value: item.id,
                        text: item.name,
                    }
                })
                address.province = arr
                // address.province = data
            } else if (level == 1) {
                let arr = data.map(item => {
                    return {
                        value: item.id,
                        text: item.name,
                    }
                })
                address.city = arr
            } else if (level == 2) {
                let arr = data.map(item => {
                    return {
                        value: item.id,
                        text: item.name,
                    }
                })
                address.town = arr

            }
        } else {
            Taro.showToast({
                title: message,
                icon: 'none',
                duration: 2000
            })
        }
    } catch (error) {
        Taro.showToast({
            title: "获取地址错误！",
            icon: 'none',
            duration: 2000
        })

    }

}
const formData = ref({
    linkman: "",
    phone: "",
    address: ""
})
const validateValue = () => {
    if (!formData.value.linkman) {
        Taro.showToast({
            title: "请输入收货人姓名",
            icon: 'none',
            duration: 2000
        })
        return false
    }
    if (!formData.value.phone) {
        Taro.showToast({
            title: "请输入收货人手机号",
            icon: 'none',
            duration: 2000
        })
        return false

    }

    if (!province.value) {
        Taro.showToast({
            title: "请选择省份",
            icon: 'none',
            duration: 2000
        })
        return false
    }

    if (!city.value) {
        Taro.showToast({
            title: "请选择城市",
            icon: 'none',
            duration: 2000
        })
        return false
    }
    if (!town.value) {
        Taro.showToast({
            title: "请选择区(县)",
            icon: 'none',
            duration: 2000
        })
        return false
    }
    if (!formData.value.address) {
        Taro.showToast({
            title: "请输入收货人详细地址",
            icon: 'none',
            duration: 2000
        })
        return false

    }
    return true
    // if ()

}
//保存地址
const saveAddress = async () => {
    if (!validateValue()) {
        return
    }
    let params = {
        ...formData.value,
        defaultRefundState: defaultRefundState.value ? 1 : 0,
        defaultState: defaultState.value ? 1 : 0,
        areaName: town.value,
        areaCode: townId.value[0],
    }
    if (addressId.value) {
        params.id = addressId.value
    }
    try {
        const { data, state, message } = await addressApi.EditAddress(params)
        if (state == 200) {
            Taro.showToast({
                title: "保存成功",
                icon: 'none',
                duration: 2000
            })
            setTimeout(() => {
                Taro.navigateBack()
            }, 1000)
        } else {
            Taro.showToast({
                title: message,
                icon: 'none',
                duration: 2000
            })
        }
    } catch (error) {
        Taro.showToast({
            title: "保存地址错误！",
            icon: 'none',
            duration: 2000
        })
    }
}
const showAddress1 = () => {
    showPopup1.value = !showPopup1.value
}
const showAddress2 = () => {
    if (province.value == '') {
        Taro.showToast({
            title: "请先选择省份",
            icon: 'none',
            duration: 2000
        })
        return
    }
    showPopup2.value = !showPopup2.value
}
const showAddress3 = () => {
    if (city.value == '') {
        Taro.showToast({
            title: "请先选择省份-城市",
            icon: 'none',
            duration: 2000
        })
        return
    }
    showPopup3.value = !showPopup3.value
}
const confirm1 = async (e) => {
    console.log(e, "e");
    province.value = e.selectedOptions[0].text
    provinceId.value = [e.selectedOptions[0].value]
    showPopup1.value = false
    getLevelArea(1, e.selectedOptions[0].value)


}
const confirm2 = async (e) => {
    console.log(e, "e");
    city.value = e.selectedOptions[0].text
    cityId.value = [e.selectedOptions[0].value]
    showPopup2.value = false
    getLevelArea(2, e.selectedOptions[0].value)


}
const confirm3 = async (e) => {
    console.log(e, "e");
    town.value = e.selectedOptions[0].text
    townId.value = [e.selectedOptions[0].value]
    showPopup3.value = false
}



</script>
<style lang="less">
.nut-checkbox__icon {
    color: #5232B7 !important;
}

.add-address-container {
    padding: 0 20px;

    .footer-btn {
        margin-top: 60px;
        padding: 0 20px;


    }

}
</style>